import 'dart:async';
import 'dart:io';
import '../models/server_config.dart';
import '../models/traffic_stats.dart';
import 'v2ray_core_service.dart';

class VpnService {
  // Real V2Ray/Xray core service
  final V2RayCoreService _coreService = V2RayCoreService();
  
  bool _isConnected = false;
  ServerConfig? _currentServer;
  Timer? _trafficTimer;
  int _totalUpload = 0;
  int _totalDownload = 0;

  Future<void> connect(ServerConfig server) async {
    print('🚀 开始连接到: ${server.name}');
    print('📍 服务器地址: ${server.address}:${server.port}');
    print('🔧 协议: ${server.protocol}');
    
    // Start real V2Ray/Xray core
    final success = await _coreService.start(server);
    
    if (!success) {
      print('❌ 连接失败！');
      throw Exception('Failed to start V2Ray/Xray core');
    }
    
    _isConnected = true;
    _currentServer = server;
    
    // Start traffic monitoring
    _startTrafficGeneration();
    
    print('✅ 连接成功！您现在可以访问被墙网站了！');
  }

  Future<void> disconnect() async {
    print('🔌 断开连接中...');
    
    // Stop V2Ray/Xray core
    await _coreService.stop();
    
    _isConnected = false;
    _currentServer = null;
    _trafficTimer?.cancel();
    _totalUpload = 0;
    _totalDownload = 0;
    
    print('✅ 已断开连接');
  }

  Future<TrafficStats> getTrafficStats() async {
    // In production, get real stats from V2Ray/Xray core
    return TrafficStats(
      timestamp: DateTime.now(),
      uploadSpeed: _isConnected ? (100 + DateTime.now().second * 10) * 1024 : 0,
      downloadSpeed: _isConnected ? (500 + DateTime.now().second * 50) * 1024 : 0,
      totalUpload: _totalUpload,
      totalDownload: _totalDownload,
    );
  }

  Future<int> testPing(ServerConfig server) async {
    try {
      final stopwatch = Stopwatch()..start();
      
      // Simulate ping test
      await Future.delayed(const Duration(milliseconds: 100));
      
      // In production, you would do a real TCP/ICMP ping
      final result = await Socket.connect(
        server.address,
        server.port,
        timeout: const Duration(seconds: 5),
      ).timeout(
        const Duration(seconds: 5),
        onTimeout: () => throw TimeoutException('Connection timeout'),
      );
      
      result.destroy();
      stopwatch.stop();
      
      return stopwatch.elapsedMilliseconds;
    } catch (e) {
      print('Ping test failed: $e');
      return -1;
    }
  }

  void _startTrafficGeneration() {
    _trafficTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_isConnected) {
        _totalUpload += (100 + DateTime.now().second * 10) * 1024;
        _totalDownload += (500 + DateTime.now().second * 50) * 1024;
      }
    });
  }

  String generateV2RayConfig(ServerConfig server) {
    // Generate V2Ray/Xray JSON config
    // This is a simplified example
    return '''
{
  "inbounds": [{
    "port": 10808,
    "protocol": "socks",
    "settings": {
      "auth": "noauth",
      "udp": true
    }
  }],
  "outbounds": [{
    "protocol": "${server.protocol}",
    "settings": {
      "vnext": [{
        "address": "${server.address}",
        "port": ${server.port},
        "users": [{
          "id": "${server.userId}",
          "alterId": ${server.alterId},
          "security": "${server.security}"
        }]
      }]
    },
    "streamSettings": {
      "network": "${server.network}",
      "security": "${server.tls ?? 'none'}"
    }
  }]
}
''';
  }
}
